package com.ruoyi.common.utils;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import javax.validation.constraints.NotNull;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * ClassName: AesEncrypt
 * Function:  TODO
 * Date:      2022/5/26 10:54
 * author     yu
 * version    V1.0
 */
public final class AesEncryptUtils {

    private AesEncryptUtils() {
        //构造器
    }

    /**
     * 对明文加密
     *
     * @param content 明文
     * @param key     密钥
     * @return
     */
    public static String encrypt(String content, String key) {
        //加密为16进制表示
        return getAes(key).encryptHex(content);
    }

    /**
     * 对密文解密
     *
     * @param encryptContent 密文
     * @param key            密钥
     * @return
     */
    public static String decrypt(String encryptContent, String key) {
        // 解密为字符串
        return getAes(key).decryptStr(encryptContent, CharsetUtil.CHARSET_UTF_8);
    }

    @NotNull
    private static AES getAes(String key) {
        if (key != null && key.length() != 16) {
            throw new RuntimeException("密钥长度需为16位");
        }
        //构建
        return new AES(Mode.ECB, Padding.PKCS5Padding, key.getBytes());
    }

    public static void mainForNormal(String[] args) {
        String ds = encrypt("test明文", "1234567890123456");
        System.out.println(ds);
        System.out.println(decrypt(ds, "1234567890123456"));
    }


    /**
     * 加密
     *
     * @param content  需要加密的内容
     * @param password 加密密码
     * @return
     */
    public static byte[] encryptNew(String content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            return result; // 加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * 解密的时候要传入byte数组
     *
     * @param content  待解密内容
     * @param password 解密密钥
     * @return
     */
    public static byte[] decryptNew(byte[] content, String password) {
        try {
            KeyGenerator kgen = KeyGenerator.getInstance("AES");
            kgen.init(128, new SecureRandom(password.getBytes()));
            SecretKey secretKey = kgen.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
            Cipher cipher = Cipher.getInstance("AES");// 创建密码器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(content);
            return result; // 加密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    private static final String AES = "AES";
    private static final String SP = "SHA1PRNG";
    private static final String CHARACTER = "utf-8";

    /*** 对原字符串串进⾏⾏行加密 ** @param content * 原字符串串 * @return */
    public static String encodeForSishui(String content, String encodeRules) {
        try {
            KeyGenerator kgt = KeyGenerator.getInstance(AES);
            SecureRandom secureRandom = SecureRandom.getInstance(SP);
            secureRandom.setSeed(encodeRules.getBytes());
            kgt.init(128, secureRandom);
            SecretKey secretKey = kgt.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES);
            Cipher cipher = Cipher.getInstance(AES);
            byte[] byteContent = content.getBytes(CHARACTER);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = cipher.doFinal(byteContent);
            // 对sign进⾏⾏行编码，防⽌⽌加号变为空格
            return URLEncoder.encode(parseByte2HexStrForSishui(result), "UTF-8");
        } catch (Exception e) {
            throw new RuntimeException("encode error");
        }
    }

    /*** 对加密的字符串串解密 ** @param content * 加密的字符串串 * @return */
    public static String decodeForSiShui(String content, String encodeRules) {
        try {
            // 对sign进⾏⾏行解码
            byte[] decryptFrom = parseHexStr2ByteForSishui(URLDecoder.decode(content, "UTF-8"));
            KeyGenerator kgt = KeyGenerator.getInstance(AES);
            SecureRandom secureRandom = SecureRandom.getInstance(SP);
            secureRandom.setSeed(encodeRules.getBytes());
            kgt.init(128, secureRandom);
            SecretKey secretKey = kgt.generateKey();
            byte[] enCodeFormat = secretKey.getEncoded();
            SecretKeySpec key = new SecretKeySpec(enCodeFormat, AES);
            Cipher cipher = Cipher.getInstance(AES); // 创建密码器器
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            byte[] result = cipher.doFinal(decryptFrom);
            return new String(result); // 加密
        } catch (
                Exception e) {
            return null;
        }
    }

    /*** 将⼆⼆进制转换成16进制 ** @param buf * @return */
    private static String parseByte2HexStrForSishui(byte buf[]) {
        return new String(Base64.getEncoder().encodeToString(buf));
    }

    /*** 将16进制转换为⼆⼆进制 ** @param hexStr * @return */
    private static byte[] parseHexStr2ByteForSishui(String hexStr) {
        return Base64.getDecoder().decode(hexStr);
    }

    public static void main(String[] args) {
//        String CDNO = "{\"companyCode\": \"test\",\"auth\":1555407227,\"username\": \"123456789\"}";
        String CDNO = "9";
        String encodeRules = "1234567890adbcde";
        String encode = encodeForSishui(CDNO, encodeRules);
        System.out.println("test encode:" + encode);
//        System.out.println("demo encode:bHwXyaQzi6B80L01X%2FdDVhzT9wg58rR3vP6NpDmqnN14KCKgmsX%2BmcqTPz5%2F79w7Ko2PKmqk6hupFSqDFlbcLbTMRnhataKrZKUOkvxGnpg%3D");
//        String decode = decodeForSiShui("bHwXyaQzi6B80L01X%2FdDVhzT9wg58rR3vP6NpDmqnN14KCKgmsX%2BmcqTPz5%2F79w7sC%2BgOav9kPwfJ9SzfbPMBZS6mO6RMYO0IAuZeM1npE8%3D", encodeRules);
        String decode = decodeForSiShui(encode, encodeRules);
        System.out.println("decode:" + decode);
        System.out.printf("完成\n\r");
    }

}
